// pages/problem/problem.js
import utils from "../../utils/util"
/**
 * 全局数据中
 * problemLunchData 
 * 结构应该如下
 * {
        type: "exercise",
        problemnum: 0,
        paper: {
            total: 一个数字表示试卷题目总数,
            problems: 一个列表内容为每道题的题目ID 对于type为contest则没有该属性
        }
    }
 * 

 * 作答历史
 * answerHistory
 * [{
        problemid: 问题id,
        problemnum: 试卷题号,
        submitted: user_answer,
        answer: answer,
        correct: correct （0/1）
    }]
 */


const app = getApp()
const MULTIPLE_HEAD = "mu-"
const UNSELECT_TYPE = "problem-option-unselect"
const RIGHT_TYPE = "problem-option-right"
const WRONG_TYPE = "problem-option-wrong"
const SELECTED_TYPE = "problem-option-selected"
const SINGLE_CHOICE = "single"
const MULTIPLE_CHOICE = "multiple"
const BINARY_CHOICE = "binary"
const COMPLETION = "completion"
const COMPLETION_KEY = COMPLETION + "input"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        /**
         * 加载该页面时应在全局data中设置
         * 对应结构应该如下
         * {
         *  type: "exercise",
         *  problemid:  1,   //题目在题库中的编号
         *  total: 1,
         *  problemnum: 1
         * }
         * 
         * {
         *  type: "contest",
         *  contestid:  1,   //比赛号
         *  problemnum: 1
         * }
         * 
         * {
         *  type: "review",
         *  problemnum: 2   //题目在本次练习的编号
         * }
         */
        lunchData: {
            type: 'contest',
            passedTime: 0,
        },
        problemTimeData: {
            passedTime: 0,
            timeLimit: 10
        },
        resultData: null,
        textAreaValue: "",
        navBarData: app.globalData.navBarData
    },

    navBack: function(){
        wx.navigateBack({
            delta: 1,
        }).catch(function () {
            wx.switchTab({
                url: '/pages/exercise/leaderboard/leaderboard',
            })
        })
    },


    setTextArea: function () {
        this.setData({
            textAreaValue: ""
        })
    },

    setlunchData: function () {
        this.setTextArea()
        let lunchData = {}
        let originLunchData = app.globalData.problemLunchData
        lunchData.type = originLunchData.type
        let problemnum = originLunchData.problemnum
        lunchData.problemnum = problemnum
        if (lunchData.type == "exercise") {
            lunchData.problemid = originLunchData.paper.problems[problemnum - 1]
            lunchData.total = originLunchData.paper.total
        } else if (lunchData.type == "contest") {
            lunchData = {
                ...originLunchData
            }
            lunchData.total = lunchData.total_number
        } else if (lunchData.type == "review") {
            let allHistory = app.globalData.answerHistory
            let resultData
            lunchData.total = allHistory.length
            allHistory.forEach(element => {
                if (element.problemnum == lunchData.problemnum) {
                    resultData = element
                    return false
                }
            });
            lunchData.problemid = resultData.problemid
            this.setData({
                resultData: resultData
            })
        } else {
            wx.showToast({
                title: '未知错误',
                icon: "error"
            })
            wx.navigateBack({
                delta: 1
            })
        }
        this.setData({
            lunchData: lunchData
        })
    },

    /**
     * 以下部分方法为数据绑定方法
     */

    /**
     * 多选单选的事件处理函数，调用相应的处理函数继续处理设定选项style，并设定check值
     * @param {*} event 
     */
    handler: function (event) {
        if (this.data.lunchData.type == "review") {
            return
        } else {
            this.choiceQuestionHandler(event)
        }
    },
    choiceQuestionHandler: function (event) {
        let problemType = this.data.problemData.type
        let id = event.currentTarget.dataset.id
        if (problemType == SINGLE_CHOICE || problemType == BINARY_CHOICE) {
            this.singleChoiceHandler(id)
        } else if (problemType == MULTIPLE_CHOICE) {
            this.multipleChoiceHandler(id)
        } else {
            console.error("无法处理的问题类型")
        }
    },
    singleChoiceHandler: function (id) {
        let problemData = this.data.problemData
        let options = problemData.options
        for (let i = 0; i < options.length; ++i) {
            if (i == id) {
                options[i].checked = true
                options[i].type = SELECTED_TYPE
            } else {
                options[i].checked = false
                options[i].type = UNSELECT_TYPE
            }
        }
        problemData.options = options
        this.setData({
            problemData: problemData
        })
    },
    multipleChoiceHandler: function (id) {
        let problemData = this.data.problemData
        let options = problemData.options
        if (!options[id].checked) {
            options[id].checked = true
            options[id].type = MULTIPLE_HEAD + SELECTED_TYPE
        } else {
            options[id].checked = false
            options[id].type = MULTIPLE_HEAD + UNSELECT_TYPE
        }
        problemData.options = options
        this.setData({
            problemData: problemData
        })
    },
    completionInput: function (event) {
        this.setData({
            textAreaValue: event.detail.value
        })
    },
    nextProblemHandler: function (event) {
        let offset = event.currentTarget.dataset.id
        app.globalData.problemLunchData.problemnum = app.globalData.problemLunchData.problemnum + offset
        this.onLoad()
    },
    returnHandler: function (e) {
        wx.navigateBack({
            delta: 1,
        })
    },

    /**
     * 以下为提交相关方法
     *  
     */
    choiceSubmit: function (e) {
        let that = this
        let data = {}
        let ans = ""
        this.data.problemData.options.forEach(element => {
            if (element.checked) {
                ans = ans + element.index
            }
        });
        if (ans == '') {
            wx.showToast({
                title: '请作答',
                icon: "error"
            })
            return
        }
        data.user_answer = ans
        this.submitRequest(data)
    },
    completionSubmit: function (e) {
        let userans = this.data.textAreaValue
        if (userans) {
            let data = {
                user_answer: userans
            }
            this.submitRequest(data)
        } else {
            wx.showToast({
                title: '答案不能为空',
                icon: "error"
            })
        }
    },
    submitRequest: function (data) {
        let that = this
        // 取消倒计时提交
        try {
            console.log("取消自动提交")
            clearTimeout(that.data.autoSubmitId)
        } catch (e) {
            console.error(e)
        }

        wx.showLoading({
            title: '提交中',
            mask: true
        })
        let url, method
        if (this.data.lunchData.type == "exercise") {
            url = utils.APIS.checkExerciseProblem.url
            method = utils.APIS.checkExerciseProblem.method
            data.problem_id = this.data.lunchData.problemid
        } else {
            url = utils.APIS.submitContestProblem.url
            method = utils.APIS.submitContestProblem.method
            data.contestid = this.data.lunchData.contestid
            data.problemnum = this.data.problemData.problemnum
        }

        utils.request({
            url: url,
            method: method,
            data: data
        }).then(function (res) {
            wx.hideLoading().catch(function () {})
            // 练习时存储答案
            if (that.data.lunchData.type == "exercise") {
                let history = app.globalData.answerHistory
                if (!history) {
                    history = []
                }
                let resData = {
                    problemid: that.data.lunchData.problemid,
                    problemnum: that.data.lunchData.problemnum,
                    submitted: data.user_answer,
                    answer: res.data.answer,
                    correct: res.data.correct
                }
                history.push(resData)
                app.globalData.answerHistory = history

                // 修改problemNum重新渲染页面为下一题
                let originLunchData = app.globalData.problemLunchData
                let totalNum = originLunchData.paper.total
                let problemnum = originLunchData.problemnum
                problemnum++
                app.globalData.problemLunchData.problemnum = problemnum
                if (problemnum <= totalNum) {
                    that.onLoad()
                } else {
                    let outcomeLunchData = {
                        type: "exercise"
                    }
                    that.setDataAndNavToOutCome(outcomeLunchData)
                }
            } else { //比赛提交后设置路由或刷新页面
                let ret = res.data.ret
                if (ret != 0 && ret != 1) {
                    wx.showToast({
                        title: ret.data.msg,
                        icon: 'error'
                    })
                    console.error(ret)
                } else {
                    //超时或正常，都进行数据修改或结束
                    if (res.data.msg == 'Timeout' || ret == 1) {
                        utils.vibrateShort()
                        wx.showToast({
                            title: '超时',
                            icon: 'error'
                        }).finally(function () {
                            if (that.data.problemData.problemnum >= that.data.lunchData.total) {
                                console.log("做完了")
                                wx.redirectTo({
                                    url: '/pages/exam/examfinish/exam-finish',
                                })
                            } else {
                                console.log("下一题")
                                that.onLoad()
                            }
                        })
                    } else if (res.data.msg == 'Success') {
                        if (that.data.problemData.problemnum >= that.data.lunchData.total) {
                            console.log("做完了")
                            wx.redirectTo({
                                url: '/pages/exam/examfinish/exam-finish',
                            })
                        } else {
                            console.log("下一题")
                            that.onLoad()
                        }
                    } else {
                        console.error(ret.data)
                    }
                }
            }
        }).catch(function (e) {
            wx.hideLoading().catch(function () {})
        }).finally(function (e) {})

    },

    /**
     * 设定数据并路由到结果展示界面
     * 目前路由了一个type
     * @param {*} data : {type: 'exercise'}
     */
    setDataAndNavToOutCome: function (data) {
        data = JSON.stringify(data)
        let url = '/pages/outcome/outcome?data=' + data
        wx.redirectTo({
            url: url
        })
    },


    startCountDown: function () {
        console.log("start count")
        this.data.progress.startCount()
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            textAreaValue: "",
            hasload: true
        })
        let that = this
        that.setlunchData()
        wx.showLoading({
            title: '正在获取题目',
            mask: true
        })
        let data = that.data.lunchData.type == "contest" ? {
            contestid: that.data.lunchData.contestid
        } : {
            id: that.data.lunchData.problemid
        }
        let url = that.data.lunchData.type == "contest" ? utils.APIS.getContestProblem.url : utils.APIS.getExerciseProblem.url
        let method = that.data.lunchData.type == "contest" ? utils.APIS.getContestProblem.method : utils.APIS.getExerciseProblem.method

        // 请求题目
        utils.request({
            url: url,
            method: method,
            data: data
        }).then(function (res) {
            wx.hideLoading()
            if (res.data.ret == 0) {
                let problemTimeData = {}
                let problemData = {
                    ...res.data
                }

                if (that.data.lunchData.type != 'contest') {
                    problemData.problemnum = that.data.lunchData.problemnum
                }

                if (problemData.type != COMPLETION) {
                    let myOptions = []
                    let cnt = 0
                    problemData.options.forEach(element => {
                        let option = {
                            option: element,
                            index: String.fromCharCode('A'.charCodeAt() + cnt),
                            type: (problemData.type == MULTIPLE_CHOICE ? MULTIPLE_HEAD : "") + UNSELECT_TYPE
                        }
                        cnt++
                        myOptions.push(option)
                    });
                    problemData.options = myOptions
                    //选择题题目展示处理
                    console.log("problem data", problemData)
                    if (that.data.lunchData.type == "review") {
                        let stylehead = problemData.type == MULTIPLE_CHOICE ? MULTIPLE_HEAD : ""
                        let history = that.data.resultData
                        let answer = [...history.answer]
                        let userAns
                        if (history.submitted) {
                            userAns = [...history.submitted]
                        } else {
                            userAns = []
                        }
                        let redList = []
                        userAns.forEach(element => {
                            if (!answer.includes(element)) {
                                redList.push(element)
                            }
                        });
                        problemData.options.forEach(element => {
                            if (redList.includes(element.index)) {
                                element.type = stylehead + WRONG_TYPE
                            }
                            if (answer.includes(element.index)) {
                                element.type = stylehead + RIGHT_TYPE
                            }
                        });
                    }
                }
                if (that.data.lunchData.type == 'contest') {
                    let timeLimit = that.data.lunchData.time_limited[problemData.type]

                    problemTimeData.timeLimit = timeLimit
                    problemTimeData.passedTime = timeLimit - problemData.time
                    problemTimeData.time = problemData.time
                    let emptyAnsData = {
                        user_answer: ""
                    }
                    if (problemTimeData.time < 0) {
                        //提交空答案
                        that.setData({
                            problemData: problemData
                        })
                        console.log("特殊超时提交")
                        that.submitRequest(emptyAnsData)
                        return
                    }
                    //开始倒计时
                    that.setData({
                        problemTimeData: problemTimeData
                    })
                    if (that.data.progress) {
                        that.startCountDown()
                    }
                    let autoSubmit = setTimeout(function () {
                        console.log("超时提交")
                        that.submitRequest(emptyAnsData)
                    }, problemTimeData.time * 1000)
                    that.setData({
                        autoSubmitId: autoSubmit,
                        'lunchData.problemnum': problemData.problemnum, //lunchdata中Problemnum从0开始计数
                        problemData: problemData
                    })
                } else {
                    that.setData({
                        problemData: problemData
                    })
                }

            } else {
                if (res.data.ret == 1 && res.data.msg === 'finished already') {
                    wx.redirectTo({
                        url: '/pages/exam/examfinish/exam-finish',
                    })
                }
                wx.showToast({
                    title: res.data.msg,
                    icon: "error"
                })
            }
        }).catch(function (res) {
            wx.hideLoading()
        }).finally(function (res) {})

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        if (this.data.lunchData.type == 'contest') {
            let progress = this.selectComponent("#progress")
            this.setData({
                progress: progress
            })
            this.startCountDown()
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        utils.initGlobalData(this)
        if (!this.data.hasload) {
            this.onLoad()
        }

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        try {
            console.log("取消自动提交")
            clearTimeout(this.data.autoSubmitId)
        } catch (e) {
            console.error(e)
        }
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})